const express = require('express');
let router = express.Router();
let myQuery = require('../tools/db');
let {apiUrl} = require('../tools/config');

// 地区接口
router.get('/area',async (req,res,next)=>{
    let sql = `SELECT * FROM e_area;`;
    let [err,result] = await myQuery(sql);
    if(err){
        next({code:500,msg:err});
        return;
    }
    res.send({code:200,msg:'ok',result});
})
// 年级
router.get('/grade',async (req,res,next)=>{
    let sql = `SELECT * FROM e_grade;`;
    let [err,result] = await myQuery(sql);
    if(err){
        next({code:500,msg:err});
        return;
    }
    res.send({code:200,msg:'ok',result});
})
// 考试类型
router.get('/category',async (req,res,next)=>{
    let sql = `SELECT * FROM e_category;`;
    let [err,result] = await myQuery(sql);
    if(err){
        next({code:500,msg:err});
        return;
    }
    res.send({code:200,msg:'ok',result});
})
// 科目
router.get('/subject',async (req,res,next)=>{
    let sql = `SELECT * FROM e_subject;`;
    let [err,result] = await myQuery(sql);
    if(err){
        next({code:500,msg:err});
        return;
    }
    res.send({code:200,msg:'ok',result});
})
// 课程列表
router.get('/courselist',async (req,res,next)=>{
    let{pagenum=6,page=1,type=1, area='',subject='',grade='',categroy=''} = req.query;
    let startNum = (page - 1) * pagenum;
    let whereStr = '';
    if(area != ''){
        whereStr += ` AND area_name = '${area}'`;
    }
    if(subject != ''){
        whereStr += ` AND subject_name = '${subject}'`;
    }
    if(grade != ''){
        whereStr += ` AND grade_name = '${grade}'`;
    }
    if(categroy != ''){
        whereStr += ` AND categroy_name = '${categroy}'`;
    }
    let sql = `SELECT COUNT(*) AS totals FROM e_course WHERE type=${type};`;
    let [,[{totals}]] = await myQuery(sql);
    let allPage = Math.ceil(totals / pagenum);
    let sql1 = `SELECT id,cid,CONCAT('${apiUrl}','course/',image_src) AS image_src,title,price,category_name,type,type_name,area_name,subject_name,grade_name FROM e_course WHERE type=${type}${whereStr} LIMIT ${startNum}, ${pagenum};`;
    let [err,result] = await myQuery(sql1);
    if(err){
        next({code:500,msg:err});
        return;
    }
    res.send({code:200,msg:'ok',pagenum,page,allPage,totals,result});
})

module.exports = router;